/* ====================================================================
 * (#)Header: FileDataProvider.java
 * (#)Revision: 
 * (#)Date Created: 2011-04-01
 * (#)Created By: Karol Wozniak
 * ====================================================================
 *
 * Copyright (c) 2007 karolak .  All rights reserved.
 *
 * ====================================================================
 * 
 * The software application represented here is the sole property of 
 * karolak. Its unauthorized utilization is expressly prohibited.
 * 
 * ====================================================================
 */
package com.karolak.data.file;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * <code>FileDataProvider</code> is ....
 * 
 * @author <a href="mailto:kwozniak@hotmail.com">Karol Wozniak</a>
 */
public class FileDataProvider {

	public static double[][] createSignal(String fileName, int sampling) {
		List<String> list = readFile(fileName);
		List<Double> x = new ArrayList<Double>();
		List<Double> y = new ArrayList<Double>();
		double[][] data = new double[2][];

		SimpleDateFormat df = new SimpleDateFormat("MMddyyHHmmss");
		for (int i = 0; i < list.size(); i++) {
			if (i % sampling == 0) {
				String[] ar = list.get(i).split(",");
				if (ar.length > 3) {
					x.add(parseDate(df, ar[0] + ar[1]));
					y.add(Double.valueOf(ar[3]));
				}
			}
		}
		System.out.println("dataList i:" + list.size() + ", sampling:" + sampling);

		data[0] = toArray(x);
		data[1] = toArray(y);
		return data;
	}

	protected static double[] toArray(List<Double> list) {
		double[] ar = new double[list.size()];
		for (int i = 0; i < ar.length; i++) {
			ar[i] = list.get(i);
		}
		return ar;
	}

	protected static double parseDate(SimpleDateFormat df, String str) {
		long l = 0;
		try {
			l = df.parse(str).getTime();
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
		return Double.valueOf(l);
	}

	public static List<String> readFile(String fileName) {
		FileInputStream fs = null;
		try {
			fs = new FileInputStream(fileName);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
		return toList(fs);
	}

	protected static List<String> toList(InputStream is) {
		List<String> list = new ArrayList<String>();
		try {
			DataInputStream in = new DataInputStream(is);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String str;
			while ((str = br.readLine()) != null) {
				if (str.startsWith("#")) {
					continue;
				}
				list.add(str);
			}
			is.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return list;
	}
}
